package cn.cmvideo.xworld.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import cn.cmvideo.xworld.activity.BaseActivity;
import cn.cmvideo.xworld.model.Config;
import cn.cmvideo.xworld.model.Global;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class HttpUtils {
	/**
	 * 无网络
	 */
	public static final int NO_NETWORK = -1;
	/**
	 * wifi网络
	 */
	public static final int WIFI = 1;
	/**
	 * wap网络
	 */
	public static final int WAP = 2;
	/**
	 * net网络
	 */
	public static final int NET = 3;

	private static String tail = null;

	/**
	 * 请求网络数据并写成文件.true:成功； false：失败
	 */
	public static boolean requestData(BaseActivity activity, String url, int method, List<NameValuePair> paramPair, boolean isGetCache) {
		// playerType = 1 为 3gp rtsp流， = 2 为 融创 file流， = 3 为华为 pem http流
		if (url.contains("?")) {
			tail = "&imsi=" + Util.md5(Config.get(activity, "tokenIMSI")) + "&random=" + Config.get(activity, "tokenRandom") + "&counter=" + Config.get(activity, "tokenCounter")
					+ "&tkInfo=" + Util.md5(Config.get(activity, "token") + Util.getUserAgent() + Config.get(activity, "tokenCounter")) + "&sdkVersion=" + Global.SDK_VERSION + "&playerType=4&netSpeed=2&isSupContSet=1";
		} else {
			tail = "?imsi=" + Util.md5(Config.get(activity, "tokenIMSI")) + "&random=" + Config.get(activity, "tokenRandom") + "&counter=" + Config.get(activity, "tokenCounter")
					+ "&tkInfo=" + Util.md5(Config.get(activity, "token") + Util.getUserAgent() + Config.get(activity, "tokenCounter")) + "&sdkVersion=" + Global.SDK_VERSION + "&playerType=4&netSpeed=2&isSupContSet=1";
		}

		L.i("HttpUtils.requestData=========================in");
		boolean flag = false;
		try {
			String fileName = Util.md5(url);
			FileUtils.deleteFile("xworld/" + fileName);
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpConnectionParams.setStaleCheckingEnabled(params, true);
			HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
			HttpConnectionParams.setSoTimeout(params, 10 * 1000);
			HttpConnectionParams.setSocketBufferSize(params, 8192);
			HttpClientParams.setRedirecting(params, true);

			SchemeRegistry schemeRegistry = new SchemeRegistry();
			schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

			ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

			DefaultHttpClient httpClient = new DefaultHttpClient(manager, params);

			httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
				public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
					request.setHeader("User-Agent", Util.getUserAgent());
					request.setHeader("X_UP_CLIENT_CHANNEL_ID", Global.CHANNEL_ID);
					request.setHeader("x-up-bear-type", "WLAN");
					request.setHeader("Content-Type", "application/x-www-form-urlencoded");
					request.setHeader("Connection", "Keep-Alive");
				}
			});

			try {
				HttpResponse httpResponse = null;
				L.i("url================" + url + tail);
				if (method == GetDataThread.METHOD_GET) {
					HttpGet httpGet = new HttpGet(url + tail);
					httpResponse = httpClient.execute(httpGet);
				} else {
					HttpPost httpPost = new HttpPost(url);
					httpPost.setEntity(new UrlEncodedFormEntity(paramPair, HTTP.UTF_8));
					httpResponse = httpClient.execute(httpPost);
				}

				String strResult = EntityUtils.toString(httpResponse.getEntity());
				L.i("getStatusCode = " + httpResponse.getStatusLine().getStatusCode());
				if (httpResponse.getStatusLine().getStatusCode() == 200) {
					L.i("生成的文件名：" + Util.md5(url));
					if (FileUtils.isFileExist(Global.CACHE_PATH + fileName)) {
						// 当文件不存在改动时， 返回false,并不做写文件操作
						if (isGetCache && Util.md5(DataConvertUtil.xStringToJsonString(strResult)).equals(Util.md5(FileUtils.file2String(Global.CACHE_PATH + fileName, "utf-8")))) {
							flag = false;
						} else {
							FileUtils.deleteFile(Global.CACHE_PATH + fileName);
							FileUtils.string2File(DataConvertUtil.xStringToJsonString(strResult), new File(Global.CACHE_PATH + Util.md5(url)));
							flag = true;
						}
					}else{
						FileUtils.string2File(DataConvertUtil.xStringToJsonString(strResult), new File(Global.CACHE_PATH + Util.md5(url)));
						flag = true;
					}
				} else {
					L.i("Http Response Status Code = " + httpResponse.getStatusLine().getStatusCode());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		L.i("HttpUtils.requestData=========================out");
		return flag;

	}

	/**
	 * 通过图片url获取图片
	 * @param imageURL
	 * @return
	 */
	public static InputStream getStreamFromURL(String imageURL) {
		InputStream in = null;
		try {
			URL url = new URL(imageURL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			in = connection.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;

	}

	/**
	 * 获取网络当前状态
	 * @param context
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public static int getAPNType(Context context) {
		int netType = -1;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
				netType = NET;
			}

			else {
				netType = WAP;
			}

		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = WIFI;
		}
		return netType;

	}

	/**
	 * 将文件流转换为字符串
	 * @param path
	 * @return
	 */
	public static String inputStream2String(String path) {
		File f = new File(path);
		String docStr = "";
		try {
			FileReader fs = new FileReader(f);
			BufferedReader br = new BufferedReader(fs);
			String text = "";
			while ((text = br.readLine()) != null) {
				docStr += text;
			}
			br.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return docStr;
	}

	/**
	 * 获取随机数
	 * @param activity
	 * @return
	 */
	public static String getLocalRandom(BaseActivity activity) {
		String random = Config.get(activity, "tokenRandom");
		if (random == null) {
			random = String.valueOf(Util.getRandom());
			Config.set(activity, "tokenRandom", random);
			Config.set(activity, "tokenCounter", "1");
		}
		return random;
	}

	/**
	 * 获取IMSI
	 * @param activity
	 * @return
	 */
	public static String getLocalIMSI(BaseActivity activity) {
		String imsi = Config.get(activity, "tokenIMSI");
		if (imsi == null) {
			imsi = Util.getIMSI(activity);
			Config.set(activity, "tokenIMSI", imsi);
			return Util.md5(imsi);
		}
		return Util.md5(imsi);
	}

	/**
	 * 获取tokenInfo
	 * @param activity
	 * @return
	 */
	public static String getTkInfo(BaseActivity activity) {
		String token = Config.get(activity, "token");
		if (token != null) {
			L.i("token ==== " + token);
			L.i("imsi ==== " + getLocalIMSI(activity));
			L.i("counter ==== " + Config.get(activity, "tokenCounter"));
			String str = token + Util.getUserAgent() + Config.get(activity, "tokenCounter");
			return Util.md5(str);
		}
		return "";
	}
}
